package dw.fastfile.common.util;

import dw.fastfile.common.exception.BusinessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.lang.Nullable;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @description: sql语句处理
 * @author: wanghao
 * @create: 2023-01-04 14:48
 **/
public class SqlUtil {
    public static String countSql(String sql) {
        return "select count(1) num from (" + sql + " ) s";
    }

    public static int countRecord(JdbcTemplate jdbcTemplate, String sql, List<Object> params) {
        Map<String, Object> m = jdbcTemplate.queryForMap(countSql(sql), params.toArray());
        return ((Long) m.get("num")).intValue();
    }

    public static boolean isExist(JdbcTemplate jdbcTemplate, String fromSql, List<Object> params) {
        Map<String, Object> m = jdbcTemplate.queryForMap("select count(1) num  " + fromSql, params.toArray());
        return ((Long) m.get("num")).intValue() != 0;
    }

    public static boolean isExist(JdbcTemplate jdbcTemplate, String fromSql, @Nullable Object... args) {
        Map<String, Object> m = jdbcTemplate.queryForMap("select count(1) num  " + fromSql, args);
        return ((Long) m.get("num")).intValue() != 0;
    }

    public static String getInSql(Set values) {
        if (values == null || values.isEmpty()) {
            throw new BusinessException("拼接In sql 语句，入参不能为空");
        }

        Set<String> v = new HashSet<>(values.size());
        for (Object s : values) {
            v.add(s + "");
        }
        String str = String.join("','", v);
        return "('" + str + "')";
    }

}
